/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: MENG
 * Date: 2022-08-11
 * Time: 21:40
 */
public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;//记录 当前hash桶中有效数字的个数

    //默认的负载因子
    public static final float DEFAULT_LOAD_FACTOR = 0.75f;

    public HashBuck(){
        this.array = new Node[10];
        this.usedSize = 0;

    }

    /**
     * 存储key val
     * @param key
     * @param val
     */
    public void put(int key,int val) {
        Node node = new Node(key,val);
        int index = key % array.length;

        Node cur =array[index];
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //头插法
        node.next = array[index];
        array[index] = node;
        usedSize++;

        //检查负载因子
        if(loadFactor() >= DEFAULT_LOAD_FACTOR){
            //进行 扩容
            grow();
        }
    }

    private float loadFactor(){
        return usedSize*1.0f / array.length;
    }

    private void grow(){
        Node[] newArray = new Node[2*array.length];


        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null){
                Node curNext = cur.next;

                //找新的位置
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        this.array = newArray;
    }

    /**
     * 通过key值 获取val 值
     * @param key
     * @return
     */
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
        }
        return -1;
    }
}
